

namespace SharpTalk.Client.WpfApplication.ViewModels
{
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Reflection;
    using System.Threading.Tasks;
    using System.Windows.Input;
    using Core;
    using Services;
    using Views;

    public sealed class ChatRoomSearchViewModel : ViewModelBase<IChatRoomSearchView>
    {
        private List<ChatRoomDetails> _searchResult;
        private bool _isSearching = false;
        private readonly ICommand _searchCommand = null;
        private ChatRoomDetails _selectedChatRoom;

        public ChatRoomSearchViewModel(IChatRoomSearchView view)
            : base(view)
        {
            View.DataContext = this;
            View.SetIcon( Helpers.LoadImage("search_16.png") );
        }

        public ICommand SearchCommand
        {
            get { return _searchCommand ?? new BindableCommand<string>(BeginSearch); }
        }

        public List<ChatRoomDetails> SearchResult
        {
            get { return _searchResult; }
            set 
            { 
                _searchResult = value;
                NotifyPropertyChange(() => SearchResult); 
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public ChatRoomDetails SelectedChatRoom
        {
            get { return _selectedChatRoom; }
            set { _selectedChatRoom = value; NotifyPropertyChange(() => SelectedChatRoom); }
        }

        
        /// <summary>
        /// 
        /// </summary>
        public bool IsSearching
        {
            get { return _isSearching; }
            set { _isSearching = value; NotifyPropertyChange(()=>IsSearching); }
        }
        /// <summary>
        /// 
        /// </summary>
        public bool CanJoin
        {
            get { return !IsSearching && SearchResult != null && SearchResult.Any(); }
        }

        private void BeginSearch(string name)
        {
            if (ShouldTrace(TraceEventType.Verbose))TraceMethodCall(MethodBase.GetCurrentMethod());

            var t = new Task(() =>
                                 {
                                     IsSearching = true;
                                     var result = ApplicationServices.Current.FindChatRooms(name);
                                     IsSearching = false;
                                     SearchResult = result;
                                     NotifyPropertyChange(() => CanJoin);
                                 });
            t.Start();
        }
    }
}